//
//  ProjectManageViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/12/19.
//  Copyright © 2015年 hvacapp. All rights reserved.
//

#import "ProjectManageViewController.h"
#import <TPKeyboardAvoidingTableView.h>
#import "MJRefresh.h"
#import "ProjectData.h"
#import "TwoLineWithDateCell.h"
#import "Project_Step8ViewController.h"
#import "ProjectManager.h"
#import <MBProgressHUD.h>

@interface ProjectManageViewController () {
    MBProgressHUD *HUD;
    NSUInteger beginIndex;
    NSUInteger endIndex;
    NSUInteger approvedBegin;
    NSUInteger approvedEnd;
}

@property (strong, nonatomic) UISegmentedControl *segmentControl;
@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView;
@property (nonatomic,retain) NSMutableArray *dataSourceApproved;
@property (nonatomic,retain) NSMutableArray *dataSourceNotApproved;

@end

@implementation ProjectManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initData];
    [self setupViews];
    [self loadData];
    // Do any additional setup after loading the view.
}

#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"项目审核";
    
    //适配iOS7uinavigationbar遮挡tableView的问题
    if(IS_IOS7){
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"未审核项目", @"已审核项目"]];
    self.navigationItem.titleView = self.segmentControl;
    
    [self.segmentControl addTarget:self action:@selector(switchView) forControlEvents:UIControlEventValueChanged];
    
    //初始显示资讯中心
    [self.segmentControl setSelectedSegmentIndex:0];
    
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:[UIView frameWithOutNavTab] style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self refreshData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
    [self.view addSubview:self.tableView];
}

- (void)switchView {
    [self.tableView reloadData];
}

#pragma mark - 数据处理
- (void)initData {
    self.dataSourceApproved = [NSMutableArray new];
    self.dataSourceNotApproved = [NSMutableArray new];
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    approvedBegin = 0;
    approvedEnd = LIST_PAGE_ITEM_COUNTS - 1;
}

- (void)refreshData {
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        //未审核
        beginIndex = 0;
        endIndex = LIST_PAGE_ITEM_COUNTS - 1;
        [self loadAllProjectData:beginIndex andEnd:endIndex andApproved:KPROJECT_PHASE_DEAL];
    }
    else {
        //已审核
        approvedBegin = 0;
        approvedEnd = LIST_PAGE_ITEM_COUNTS - 1;
        [self loadAllProjectData:approvedBegin andEnd:approvedEnd andApproved:KPROJECT_PHASE_REVIEW];
    }
    
}

- (void)loadMoreData {
    if (_segmentControl.selectedSegmentIndex == 0) {
        //未审核
        if (self.dataSourceNotApproved.count == 0) {
            return;
        }
        // 马上进入刷新状态
        [self.tableView.mj_footer beginRefreshing];
        beginIndex = self.dataSourceNotApproved.count;
        endIndex = beginIndex + LIST_PAGE_ITEM_COUNTS - 1;
        [self loadAllProjectData:beginIndex andEnd:endIndex andApproved:KPROJECT_PHASE_DEAL];
    }
    else {
        //已审核
        if (self.dataSourceApproved.count == 0) {
            return;
        }
        // 马上进入刷新状态
        [self.tableView.mj_footer beginRefreshing];
        approvedBegin = self.dataSourceApproved.count;
        approvedEnd = approvedBegin + LIST_PAGE_ITEM_COUNTS - 1;
        [self loadAllProjectData:approvedBegin andEnd:approvedEnd andApproved:KPROJECT_PHASE_REVIEW];
    }
}

- (void)loadData {
    //未审核
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    [self loadAllProjectData:beginIndex andEnd:endIndex andApproved:KPROJECT_PHASE_DEAL];
    //已审核
    approvedBegin = 0;
    approvedEnd = LIST_PAGE_ITEM_COUNTS - 1;
    [self loadAllProjectData:approvedBegin andEnd:approvedEnd andApproved:KPROJECT_PHASE_REVIEW];
}

- (void)loadAllProjectData:(NSInteger)si andEnd:(NSInteger)ei andApproved:(NSInteger)approve {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInteger:si] forKey:@"si"];
    [param setValue:[NSNumber numberWithInteger:ei] forKey:@"ei"];
    [param setValue:[NSNumber numberWithInteger:approve] forKey:@"p"];
    
    
    [HttpClient getWithUrl:HTTP_GET_APPROVED_PROJECTS token:[[AccountManager manager]token] paramDic:param resultClass:[ProjectData class] success:^(ProjectData *obj) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            if (approve == KPROJECT_PHASE_DEAL) {
                //未审核的项目
                [self.dataSourceNotApproved removeAllObjects];
            }
            else {
                [self.dataSourceApproved removeAllObjects];
            }
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        if (obj.getReviewProjectsResult != nil && obj.getReviewProjectsResult.count > 0) {
            if (approve == KPROJECT_PHASE_DEAL) {
                //未审核的项目
                [self.dataSourceNotApproved addObjectsFromArray:obj.getReviewProjectsResult];
            }
            else {
                [self.dataSourceApproved addObjectsFromArray:obj.getReviewProjectsResult];
            }
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            if (approve == KPROJECT_PHASE_DEAL) {
                //未审核的项目
                [self.dataSourceNotApproved removeAllObjects];
            }
            else {
                [self.dataSourceApproved removeAllObjects];
            }
            [self.tableView reloadData];
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        CMLog(@"获取项目列表失败：%@", error);
    }];
}

- (void)modifyProjectApproveData:(int)isApproved forProject:(ProjectData*)data {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInt:isApproved] forKey:@"p"];
    [param setValue:data.project_id forKey:@"pid"];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    if (isApproved == 1) {
        HUD.labelText = @"设置为审核项目中...";
    }
    else {
        HUD.labelText = @"设置为未审核项目中...";
    }
    
    [HttpClient getWithUrl:HTTP_GET_APPROVE_PROJECT token:[[AccountManager manager]token] paramDic:param resultClass:[ProjectData class] success:^(ProjectData *obj) {
        //成功
        [HUD setHidden:YES];
        if (isApproved == KPROJECT_PHASE_REVIEW) {
            //把当前数据放到已认证数据源中，并从未认证数据源中删除
            [self.dataSourceNotApproved removeObject:data];
            [self.dataSourceApproved addObject:data];
        }
        else {
            [self.dataSourceApproved removeObject:data];
            [self.dataSourceNotApproved addObject:data];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        CMLog(@"设置用户认证数据失败：%@", error);
    }];
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_segmentControl.selectedSegmentIndex == 0) {
        return self.dataSourceNotApproved.count;
    } else if (_segmentControl.selectedSegmentIndex == 1) {
        return self.dataSourceApproved.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    TwoLineWithDateCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[TwoLineWithDateCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    ProjectData *item;
    if (_segmentControl.selectedSegmentIndex == 0) {
        item = [self.dataSourceNotApproved objectAtIndex:indexPath.row];
    }
    else {
        item = [self.dataSourceApproved objectAtIndex:indexPath.row];
    }
    
    NSString *detail = [NSString stringWithFormat:@"%.2f平米 %@ %@", item.area, item.owner_name, item.owner_tel];
    [cell setTitleStr:item.project_name andStatus:item.userContactName andStatusColor:CM_BLUE_COLOR andDetailStr:detail andDate:[DateTools getChYearMonthDay:item.time]];
//    [cell setTitleStr:item.house andDetailStr:detail andDate:[DateTools getChYearMonthDay:item.time]];
    
    
    //滑动按钮
    cell.rightUtilityButtons = [self rightButtons];
    cell.delegate = self;
    cell.tag = indexPath.row;
    
    return cell;
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    if (_segmentControl.selectedSegmentIndex == 1) {
        [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"取消审核"];
    }
    else {
        [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"审核项目"];
    }
    return rightUtilityButtons;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //反选
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ProjectData *item;
    int approved = 0;
    if (_segmentControl.selectedSegmentIndex == 0) {
        approved = 1;
        item = [self.dataSourceNotApproved objectAtIndex:indexPath.row];
    } else if (_segmentControl.selectedSegmentIndex == 1) {
        approved = 0;
        item = [self.dataSourceApproved objectAtIndex:indexPath.row];
    }
    //进项目报告页面
    [[ProjectManager manager]saveProject:item];
    Project_Step8ViewController *view = [Project_Step8ViewController new];
    [self.navigationController pushViewController:view animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"Cell";
    TwoLineWithDateCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[TwoLineWithDateCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    return [cell getHeight];
}

#pragma mark - 滑动按钮代理协议
/**
 *  右侧滑动按钮点击事件
 *
 *  @param cell  单元cell
 *  @param index 下标
 */
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    switch (index) {
        case 0:{
            ProjectData *item;
            int approved = 0;
            if (_segmentControl.selectedSegmentIndex == 0) {
                approved = 1;
                item = [self.dataSourceNotApproved objectAtIndex:cell.tag];
                [self modifyProjectApproveData:KPROJECT_PHASE_REVIEW forProject:item];
            } else if (_segmentControl.selectedSegmentIndex == 1) {
                approved = 0;
                item = [self.dataSourceApproved objectAtIndex:cell.tag];
                [self modifyProjectApproveData:KPROJECT_PHASE_DEAL forProject:item];
            }
            break;
        }
            
        default:
            break;
    }
    [cell hideUtilityButtonsAnimated:YES];
}


/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
